{% extends "base.html" %}

{% block title %}系统资源监控{% endblock %}

{% block head %}
{{ super() }}
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
<style>
    /* 液态玻璃效果样式 */
    .page-header {
        background: var(--glass-bg);
        backdrop-filter: var(--glass-blur);
        -webkit-backdrop-filter: var(--glass-blur);
        border: 1px solid var(--glass-border);
        border-radius: var(--border-radius);
        padding: 2rem;
        margin-bottom: 2rem;
        box-shadow: var(--glass-shadow);
        position: relative;
        overflow: hidden;
    }

    .page-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
        pointer-events: none;
        z-index: 0;
    }

    .page-header > div {
        position: relative;
        z-index: 1;
    }

    .page-title {
        font-size: 2rem;
        font-weight: 700;
        color: var(--text-primary) !important;
        margin-bottom: 0.5rem;
        text-shadow: 0 2px 4px rgba(0, 122, 255, 0.1);
    }

    .page-subtitle {
        color: var(--text-muted) !important;
        margin-bottom: 0;
    }

    .metric-card {
        background: var(--glass-bg);
        backdrop-filter: var(--glass-blur-light);
        -webkit-backdrop-filter: var(--glass-blur-light);
        border: 1px solid var(--glass-border);
        border-radius: var(--border-radius);
        box-shadow: var(--glass-shadow);
        transition: all 0.3s ease;
    }
    
    .metric-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
    }
    
    .status-normal {
        color: var(--success-color);
    }
    
    .status-warning {
        color: var(--warning-color);
    }
    
    .status-critical {
        color: var(--danger-color);
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid py-4">
    <div class="page-header mb-4">
        <div>
            <h1 class="page-title">系统资源监控</h1>
            <p class="page-subtitle">实时监控系统资源使用情况和告警信息</p>
        </div>
    </div>
        
    <!-- 服务状态指标卡片 -->
    <div class="row mb-4">
        <div class="col-12 mb-2">
            <h5>服务状态</h5>
        </div>
        <div id="services-container" class="row">
            <!-- 服务状态卡片将通过JavaScript动态添加 -->
            <div class="col-md-3 mb-4">
                <div class="card metric-card h-100">
                    <div class="card-body">
                        <h5 class="card-title">Web服务</h5>
                        <div class="d-flex align-items-center justify-content-center">
                            <i class="bi bi-globe me-2 fs-1" id="web-service-icon"></i>
                        </div>
                        <div class="text-center mt-2">
                            <span id="web-service-status">检查中...</span>
                        </div>
                        <div class="text-center mt-2">
                            <small id="web-service-uptime">-</small>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-4">
                <div class="card metric-card h-100">
                    <div class="card-body">
                        <h5 class="card-title">调度器服务</h5>
                        <div class="d-flex align-items-center justify-content-center">
                            <i class="bi bi-calendar-check me-2 fs-1" id="scheduler-service-icon"></i>
                        </div>
                        <div class="text-center mt-2">
                            <span id="scheduler-service-status">检查中...</span>
                        </div>
                        <div class="text-center mt-2">
                            <small id="scheduler-service-uptime">-</small>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-4">
                <div class="card metric-card h-100">
                    <div class="card-body">
                        <h5 class="card-title">执行器服务</h5>
                        <div class="d-flex align-items-center justify-content-center">
                            <i class="bi bi-play-circle me-2 fs-1" id="executor-service-icon"></i>
                        </div>
                        <div class="text-center mt-2">
                            <span id="executor-service-status">检查中...</span>
                        </div>
                        <div class="text-center mt-2">
                            <small id="executor-service-uptime">-</small>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-4">
                <div class="card metric-card h-100">
                    <div class="card-body">
                        <h5 class="card-title">监控服务</h5>
                        <div class="d-flex align-items-center justify-content-center">
                            <i class="bi bi-graph-up me-2 fs-1" id="monitor-service-icon"></i>
                        </div>
                        <div class="text-center mt-2">
                            <span id="monitor-service-status">检查中...</span>
                        </div>
                        <div class="text-center mt-2">
                            <small id="monitor-service-uptime">-</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 系统资源指标卡片 -->
    <div class="row mb-4">
        <div class="col-12 mb-2">
            <h5>系统资源</h5>
        </div>
        <div class="col-md-4 mb-4">
            <div class="card metric-card h-100">
                <div class="card-body">
                    <h5 class="card-title">CPU使用率</h5>
                    <div class="d-flex align-items-center justify-content-center">
                        <i class="bi bi-cpu me-2 fs-1" id="cpu-icon"></i>
                        <h2 class="mb-0 display-4" id="cpu-usage">--%</h2>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4 mb-4">
            <div class="card metric-card h-100">
                <div class="card-body">
                    <h5 class="card-title">内存使用率</h5>
                    <div class="d-flex align-items-center justify-content-center">
                        <i class="bi bi-memory me-2 fs-1" id="memory-icon"></i>
                        <h2 class="mb-0 display-4" id="memory-usage">--%</h2>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-4 mb-4">
            <div class="card metric-card h-100">
                <div class="card-body">
                    <h5 class="card-title">磁盘使用率</h5>
                    <div class="d-flex align-items-center justify-content-center">
                        <i class="bi bi-hdd me-2 fs-1" id="disk-icon"></i>
                        <h2 class="mb-0 display-4" id="disk-usage">--%</h2>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 告警历史 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card metric-card">
                <div class="card-header d-flex justify-content-between align-items-center" style="background: var(--glass-bg); border-bottom: 1px solid var(--glass-border);">
                    <h5 class="mb-0">告警历史</h5>
                    <button class="btn btn-sm btn-outline-secondary" style="border: 1px solid var(--glass-border); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light);" onclick="refreshAlertHistory()">
                        <i class="bi bi-arrow-clockwise"></i> 刷新
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th style="background: var(--glass-bg); color: var(--text-primary);">时间</th>
                                    <th style="background: var(--glass-bg); color: var(--text-primary);">状态</th>
                                    <th style="background: var(--glass-bg); color: var(--text-primary);">告警信息</th>
                                    <th style="background: var(--glass-bg); color: var(--text-primary);">系统指标</th>
                                </tr>
                            </thead>
                            <tbody id="alert-history"></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 监控配置 -->
    {% if current_user.is_administrator() %}
        <div class="row mb-4">
            <div class="col-md-6 col-12">
                <div class="card metric-card h-100">
                    <div class="card-header" style="background: var(--glass-bg); border-bottom: 1px solid var(--glass-border);">
                        <h5 class="mb-0">监控阈值配置</h5>
                    </div>
                    <div class="card-body">
                        <form id="monitor-config-form">
                            <div class="mb-3">
                                <label class="form-label">CPU使用率阈值 (%)</label>
                                <div class="row">
                                    <div class="col">
                                        <input type="number" class="form-control" id="cpu-warning" placeholder="警告阈值" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                                    </div>
                                    <div class="col">
                                        <input type="number" class="form-control" id="cpu-critical" placeholder="严重阈值" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                                    </div>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">内存使用率阈值 (%)</label>
                                <div class="row">
                                    <div class="col">
                                        <input type="number" class="form-control" id="memory-warning" placeholder="警告阈值" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                                    </div>
                                    <div class="col">
                                        <input type="number" class="form-control" id="memory-critical" placeholder="严重阈值" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                                    </div>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">磁盘使用率阈值 (%)</label>
                                <div class="row">
                                    <div class="col">
                                        <input type="number" class="form-control" id="disk-warning" placeholder="警告阈值" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                                    </div>
                                    <div class="col">
                                        <input type="number" class="form-control" id="disk-critical" placeholder="严重阈值" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary" style="background: var(--gradient-primary); border: none; box-shadow: var(--glass-shadow);">保存配置</button>
                        </form>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-12">
                <div class="card metric-card h-100">
                    <div class="card-header" style="background: var(--glass-bg); border-bottom: 1px solid var(--glass-border);">
                        <h5 class="mb-0">告警配置</h5>
                    </div>
                    <div class="card-body">
                        <form id="alert-config-form">
                        <div class="mb-3">
                            <div class="form-check form-switch" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border); border-radius: 8px; padding: 10px;">
                                <input class="form-check-input" type="checkbox" id="email-enabled">
                                <label class="form-check-label">启用邮件通知</label>
                            </div>
                        </div>
                        <div id="email-config" class="mb-3" style="display: none;">
                            <div class="mb-2">
                                <input type="text" class="form-control" id="smtp-server" placeholder="SMTP服务器" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                            </div>
                            <div class="mb-2">
                                <input type="number" class="form-control" id="smtp-port" placeholder="SMTP端口" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                            </div>
                            <div class="mb-2">
                                <input type="email" class="form-control" id="email-username" placeholder="邮箱账号" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                            </div>
                            <div class="mb-2">
                                <input type="password" class="form-control" id="email-password" placeholder="邮箱密码" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                            </div>
                            <div class="mb-2">
                                <input type="text" class="form-control" id="email-recipients" placeholder="接收邮箱（多个用逗号分隔）" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check form-switch" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border); border-radius: 8px; padding: 10px;">
                                <input class="form-check-input" type="checkbox" id="dingtalk-enabled">
                                <label class="form-check-label">启用钉钉通知</label>
                            </div>
                        </div>
                        <div id="dingtalk-config" class="mb-3" style="display: none;">
                            <div class="mb-2">
                                <input type="text" class="form-control" id="webhook-url" placeholder="Webhook URL" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                            </div>
                            <div class="mb-2">
                                <input type="text" class="form-control" id="secret-key" placeholder="加签密钥" style="background: var(--glass-bg); backdrop-filter: var(--glass-blur-light); -webkit-backdrop-filter: var(--glass-blur-light); border: 1px solid var(--glass-border);">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">通知级别</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="notify-warning">
                                <label class="form-check-label">警告</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="notify-critical">
                                <label class="form-check-label">严重</label>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary" style="background: var(--gradient-primary); border: none; box-shadow: var(--glass-shadow);">保存配置</button>
                    </form>
                </div>
            </div>
        </div>
    {% else %}
        <div class="row mb-4">
            <div class="col-12">
                <div class="card metric-card">
                    <div class="card-body text-center">
                        <p class="mb-0">配置项仅管理员可见</p>
                    </div>
                </div>
            </div>
        </div>
    {% endif %}
    </div>

    <script>
        // 状态配置
        
        // 更新状态图标
        function updateStatusIcon(id, status) {
            const icon = document.getElementById(id);
            icon.className = 'bi me-2 ' + {
                'normal': 'bi-check-circle status-normal',
                'warning': 'bi-exclamation-triangle status-warning',
                'critical': 'bi-x-circle status-critical'
            }[status];
        }
        
        // 更新服务状态图标
        function updateServiceIcon(id, online) {
            const icon = document.getElementById(id);
            if (online) {
                icon.className = 'bi bi-check-circle-fill me-2 fs-1 status-normal';
            } else {
                icon.className = 'bi bi-x-circle-fill me-2 fs-1 status-critical';
            }
        }
        
        // 获取服务状态
        async function fetchServicesStatus() {
            try {
                const response = await fetch('/api/monitor/services');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const services = await response.json();
                
                // 确保services是数组且有足够的元素
                if (!Array.isArray(services) || services.length < 4) {
                    throw new Error('服务状态数据格式不正确');
                }
                
                // 更新Web服务状态
                updateServiceIcon('web-service-icon', services[0].status);
                document.getElementById('web-service-status').textContent = services[0].status ? '在线' : '离线';
                document.getElementById('web-service-uptime').textContent = services[0].status && services[0].uptime ? `在线时长: ${services[0].uptime}` : '';
                
                // 更新调度器服务状态
                updateServiceIcon('scheduler-service-icon', services[1].status);
                document.getElementById('scheduler-service-status').textContent = services[1].status ? '在线' : '离线';
                document.getElementById('scheduler-service-uptime').textContent = services[1].status && services[1].uptime ? `在线时长: ${services[1].uptime}` : '';
                
                // 更新执行器服务状态
                updateServiceIcon('executor-service-icon', services[2].status);
                document.getElementById('executor-service-status').textContent = services[2].status ? '在线' : '离线';
                document.getElementById('executor-service-uptime').textContent = services[2].status && services[2].uptime ? `在线时长: ${services[2].uptime}` : '';
                
                // 更新监控服务状态
                updateServiceIcon('monitor-service-icon', services[3].status);
                document.getElementById('monitor-service-status').textContent = services[3].status ? '在线' : '离线';
                document.getElementById('monitor-service-uptime').textContent = services[3].status && services[3].uptime ? `在线时长: ${services[3].uptime}` : '';
            } catch (error) {
                console.error('获取服务状态失败:', error);
                // 显示错误信息，但Web服务肯定是在线的
                updateServiceIcon('web-service-icon', true);
                document.getElementById('web-service-status').textContent = '在线';
                document.getElementById('web-service-uptime').textContent = '当前页面正在运行';
                
                // 其他服务显示获取失败
                updateServiceIcon('scheduler-service-icon', false);
                document.getElementById('scheduler-service-status').textContent = '获取失败';
                document.getElementById('scheduler-service-uptime').textContent = '';
                
                updateServiceIcon('executor-service-icon', false);
                document.getElementById('executor-service-status').textContent = '获取失败';
                document.getElementById('executor-service-uptime').textContent = '';
                
                updateServiceIcon('monitor-service-icon', false);
                document.getElementById('monitor-service-status').textContent = '获取失败';
                document.getElementById('monitor-service-uptime').textContent = '';
            }
        }

        // 获取系统指标
        async function fetchMetrics() {
            try {
                // 修正API路径，使用正确的端点
                const response = await fetch('/api/monitor/metrics/system');
                const data = await response.json();
                
                // 更新CPU指标
                document.getElementById('cpu-usage').textContent = `${data.cpu.percent.toFixed(1)}%`;
                updateStatusIcon('cpu-icon', data.cpu.status);
                
                // 更新内存指标
                document.getElementById('memory-usage').textContent = `${data.memory.percent.toFixed(1)}%`;
                updateStatusIcon('memory-icon', data.memory.status);
                
                // 更新磁盘指标
                document.getElementById('disk-usage').textContent = `${data.disk.percent.toFixed(1)}%`;
                updateStatusIcon('disk-icon', data.disk.status);
            } catch (error) {
                console.error('获取系统指标失败:', error);
                // 在获取失败时显示默认值
                document.getElementById('cpu-usage').textContent = '0.0%';
                updateStatusIcon('cpu-icon', 'normal');
                
                document.getElementById('memory-usage').textContent = '0.0%';
                updateStatusIcon('memory-icon', 'normal');
                
                document.getElementById('disk-usage').textContent = '0.0%';
                updateStatusIcon('disk-icon', 'normal');
            }
        }

        // 获取告警历史
        async function fetchAlertHistory() {
            try {
                // 修正API路径，使用正确的端点
                const response = await fetch('/api/monitor/history');
                const history = await response.json();
                
                const tbody = document.getElementById('alert-history');
                tbody.innerHTML = '';
                
                if (history && history.length > 0) {
                    history.forEach(alert => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                            <td>${new Date(alert.datetime).toLocaleString()}</td>
                            <td>
                                <span class="badge ${alert.status === 'normal' ? 'bg-success' : alert.status === 'warning' ? 'bg-warning' : 'bg-danger'}">${alert.status}</span>
                            </td>
                            <td>${alert.warnings ? alert.warnings.join('<br>') : '-'}</td>
                            <td>
                                CPU: ${alert.metrics && alert.metrics.cpu ? alert.metrics.cpu.percent.toFixed(1) : '0.0'}%<br>
                                内存: ${alert.metrics && alert.metrics.memory ? alert.metrics.memory.percent.toFixed(1) : '0.0'}%<br>
                                磁盘: ${alert.metrics && alert.metrics.disk ? alert.metrics.disk.percent.toFixed(1) : '0.0'}%
                            </td>
                        `;
                        tbody.appendChild(tr);
                    });
                } else {
                    // 如果没有告警历史，显示提示信息
                    const tr = document.createElement('tr');
                    tr.innerHTML = `<td colspan="4" class="text-center">暂无告警历史</td>`;
                    tbody.appendChild(tr);
                }
            } catch (error) {
                console.error('获取告警历史失败:', error);
                // 在获取失败时显示错误提示
                const tbody = document.getElementById('alert-history');
                tbody.innerHTML = `<tr><td colspan="4" class="text-center">获取告警历史失败，请稍后重试</td></tr>`;
            }
        }

        {% if current_user.is_administrator() %}
        // 加载监控配置
        async function loadMonitorConfig() {
            try {
                // 修正API路径，使用正确的端点
                const response = await fetch('/api/monitor/config');
                const config = await response.json();
                
                // 确保配置对象和其属性存在
                if (config && config.warning_thresholds && config.critical_thresholds) {
                    document.getElementById('cpu-warning').value = config.warning_thresholds.cpu || 70;
                    document.getElementById('cpu-critical').value = config.critical_thresholds.cpu || 90;
                    document.getElementById('memory-warning').value = config.warning_thresholds.memory || 70;
                    document.getElementById('memory-critical').value = config.critical_thresholds.memory || 90;
                    document.getElementById('disk-warning').value = config.warning_thresholds.disk || 70;
                    document.getElementById('disk-critical').value = config.critical_thresholds.disk || 90;
                } else {
                    // 如果配置对象不完整，使用默认值
                    setDefaultMonitorConfig();
                }
            } catch (error) {
                console.error('加载监控配置失败:', error);
                // 在获取失败时设置默认值
                setDefaultMonitorConfig();
            }
        }
        
        // 设置默认监控配置
        function setDefaultMonitorConfig() {
            document.getElementById('cpu-warning').value = 70;
            document.getElementById('cpu-critical').value = 90;
            document.getElementById('memory-warning').value = 70;
            document.getElementById('memory-critical').value = 90;
            document.getElementById('disk-warning').value = 70;
            document.getElementById('disk-critical').value = 90;
        }

        // 加载告警配置
        async function loadAlertConfig() {
            try {
                // 修正API路径，使用正确的端点
                const response = await fetch('/api/monitor/alert/config');
                const config = await response.json();
                
                // 确保配置对象和其属性存在
                if (config && config.email && config.dingtalk && config.notification_levels) {
                    // 邮件配置
                    document.getElementById('email-enabled').checked = config.email.enabled || false;
                    document.getElementById('smtp-server').value = config.email.smtp_server || '';
                    document.getElementById('smtp-port').value = config.email.smtp_port || '25';
                    document.getElementById('email-username').value = config.email.username || '';
                    document.getElementById('email-password').value = config.email.password || '';
                    document.getElementById('email-recipients').value = config.email.to_addrs && Array.isArray(config.email.to_addrs) ? 
                        config.email.to_addrs.join(',') : '';
                    
                    // 钉钉配置
                    document.getElementById('dingtalk-enabled').checked = config.dingtalk.enabled || false;
                    document.getElementById('webhook-url').value = config.dingtalk.webhook_url || '';
                    document.getElementById('secret-key').value = config.dingtalk.secret || '';
                    
                    // 通知级别
                    document.getElementById('notify-warning').checked = config.notification_levels.includes('warning');
                    document.getElementById('notify-critical').checked = config.notification_levels.includes('critical');
                    
                    // 显示/隐藏配置区域
                    document.getElementById('email-config').style.display = config.email.enabled ? 'block' : 'none';
                    document.getElementById('dingtalk-config').style.display = config.dingtalk.enabled ? 'block' : 'none';
                } else {
                    // 如果配置对象不完整，使用默认值
                    setDefaultAlertConfig();
                }
            } catch (error) {
                console.error('加载告警配置失败:', error);
                // 在获取失败时设置默认值
                setDefaultAlertConfig();
            }
        }
        
        // 设置默认告警配置
        function setDefaultAlertConfig() {
            // 邮件配置
            document.getElementById('email-enabled').checked = false;
            document.getElementById('smtp-server').value = '';
            document.getElementById('smtp-port').value = '25';
            document.getElementById('email-username').value = '';
            document.getElementById('email-password').value = '';
            document.getElementById('email-recipients').value = '';
            
            // 钉钉配置
            document.getElementById('dingtalk-enabled').checked = false;
            document.getElementById('webhook-url').value = '';
            document.getElementById('secret-key').value = '';
            
            // 通知级别
            document.getElementById('notify-warning').checked = true;
            document.getElementById('notify-critical').checked = true;
            
            // 显示/隐藏配置区域
            document.getElementById('email-config').style.display = 'none';
            document.getElementById('dingtalk-config').style.display = 'none';
        }

        // 保存监控配置
        document.getElementById('monitor-config-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const config = {
                warning_thresholds: {
                    cpu: parseFloat(document.getElementById('cpu-warning').value),
                    memory: parseFloat(document.getElementById('memory-warning').value),
                    disk: parseFloat(document.getElementById('disk-warning').value)
                },
                critical_thresholds: {
                    cpu: parseFloat(document.getElementById('cpu-critical').value),
                    memory: parseFloat(document.getElementById('memory-critical').value),
                    disk: parseFloat(document.getElementById('disk-critical').value)
                }
            };
            
            try {
                const response = await fetch('/api/monitor/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(config)
                });
                
                if (response.ok) {
                    alert('监控配置保存成功');
                } else {
                    alert('监控配置保存失败');
                }
            } catch (error) {
                console.error('保存监控配置失败:', error);
                alert('保存监控配置失败');
            }
        });

        // 保存告警配置
        document.getElementById('alert-config-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const config = {
                email: {
                    enabled: document.getElementById('email-enabled').checked,
                    smtp_server: document.getElementById('smtp-server').value,
                    smtp_port: parseInt(document.getElementById('smtp-port').value),
                    username: document.getElementById('email-username').value,
                    password: document.getElementById('email-password').value,
                    from_addr: document.getElementById('email-username').value,
                    to_addrs: document.getElementById('email-recipients').value.split(',').map(e => e.trim())
                },
                dingtalk: {
                    enabled: document.getElementById('dingtalk-enabled').checked,
                    webhook_url: document.getElementById('webhook-url').value,
                    secret: document.getElementById('secret-key').value
                },
                notification_levels: [
                    ...(document.getElementById('notify-warning').checked ? ['warning'] : []),
                    ...(document.getElementById('notify-critical').checked ? ['critical'] : [])
                ]
            };
            
            try {
                // 修正API路径，使用正确的端点
                const response = await fetch('/api/monitor/alert/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(config)
                });
                
                if (response.ok) {
                    alert('告警配置保存成功');
                } else {
                    alert('告警配置保存失败');
                }
            } catch (error) {
                console.error('保存告警配置失败:', error);
                alert('保存告警配置失败');
            }
        });

        // 显示/隐藏配置区域
        document.getElementById('email-enabled').addEventListener('change', (e) => {
            document.getElementById('email-config').style.display = e.target.checked ? 'block' : 'none';
        });

        document.getElementById('dingtalk-enabled').addEventListener('change', (e) => {
            document.getElementById('dingtalk-config').style.display = e.target.checked ? 'block' : 'none';
        });
        {% endif %}

        // 定时更新数据
        setInterval(fetchMetrics, 5000);
        setInterval(fetchAlertHistory, 30000);
        setInterval(fetchServicesStatus, 10000);

        // 初始化加载
        fetchMetrics();
        fetchAlertHistory();
        fetchServicesStatus();
        {% if current_user.is_administrator() %}
        loadMonitorConfig();
        loadAlertConfig();
        {% endif %}
    </script>
{% endblock %}